#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <strings.h>

#include <sys/types.h>
#include <sys/stat.h>

#include "api/api.h"

struct termios oldtio;

int main(int argc, char* argv[])
{
	printf("Initializing sender\n");
	int fd = llopen(TTYS0, SENDER);
	int file_fd = open(argv[1],O_RDONLY);
	
	if (file_fd < 0)
		return -1;
		
	char buf[DATA_SIZE];
	int total_bytes = 0;
	int bytes_read = -1;
	
	llwrite(fd, argv[1], START_CONTROL_PACKET);
	
	while(bytes_read != 0)
	{
		bzero(buf, DATA_SIZE);
		bytes_read = read(file_fd,buf,DATA_SIZE); 
		if(bytes_read == 0)
			break; //end of reading file
		if(bytes_read < 0)
		{
			printf("Something bad happened to the file!\n");
			return -1; 
		}
		total_bytes += bytes_read;
		if(llwrite(fd,buf,bytes_read) != bytes_read)
			printf("llwrite() != bytes_read\n");
	}
	
	//escrever pacote de terminar transmissao
	llwrite(fd, (char*) &file_fd, END_CONTROL_PACKET);
	
	llclose(fd);
	
	printf("File sent! Bye bye\n");
	
	return 0;
}

